import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';

class TextHighlight extends StatelessWidget {
  final TextStyle _ordinaryStyle; //普通的样式
  final TextStyle _highlightStyle; //高亮的样式
  final String _content; //文本内容
  List<String> _searchContent = []; //搜索的内容
  int? maxLines = 1;
  TextOverflow overflow = TextOverflow.ellipsis;
  void Function(int)? searchContentClick;
  void Function()? unSearchClick;
  final bool caseSensitive; //是否区分大小写

  TextHighlight(this._content, this._searchContent, this._ordinaryStyle,
      this._highlightStyle,
      {super.key,
      this.maxLines = 1,
      this.overflow = TextOverflow.ellipsis,
      this.unSearchClick,
      this.searchContentClick,
      this.caseSensitive = true});

  @override
  Widget build(BuildContext context) {
    //搜索内容为空
    if (_searchContent == null || _searchContent.length <= 0) {
      // return Text(
      //   _content,
      //   style: _ordinaryStyle,
      // );
      return RichText(
          text: TextSpan(text: _content, style: _ordinaryStyle),
          overflow: overflow,
          maxLines: maxLines);
    }
    List<InlineSpan> richList = [];
    int start = 0;
    int end;
    for (var i = 0; i < _searchContent.length; i++) {
      //遍历，进行多处高亮
      while ((end = _content.indexOf(
              RegExp('${_searchContent[i]}', caseSensitive: caseSensitive),
              start)) !=
          -1) {
        //如果搜索内容在开头位置，直接高亮，此处不执行
        if (end != 0) {
          richList.add(TextSpan(
              text: _content.substring(start, end),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  unSearchClick?.call();
                },
              style: _ordinaryStyle));
          // if (unSearchClick != null) {
          // } else {
          // richList.add(TextSpan(
          //     text: _content.substring(start, end), style: _ordinaryStyle));
          // }
        }
        if (searchContentClick != null) {
          //高亮内容
          richList.add(TextSpan(
            text: _content.substring(end, end + _searchContent[i].length),
            style: _highlightStyle,
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                searchContentClick?.call(i);
              },
          ));
        } else {
          richList.add(TextSpan(
              text: _content.substring(end, end + _searchContent[i].length),
              style: _highlightStyle));
        }
        //赋值索引
        start = end + _searchContent[i].length;
      }
      //搜索内容只有在开头或者中间位置，才执行
    }
    if (start != _content.length) {
      richList.add(TextSpan(
          text: _content.substring(start, _content.length),
          style: _ordinaryStyle));
    }
    return RichText(
      text: TextSpan(children: richList),
      overflow: overflow,
      maxLines: maxLines,
    );
  }
}
